using System;
using System.Linq;
using System.Threading.Tasks;
using Gj.Galaxy.Logic;
using Unity.Services.Core;
using Unity.Services.Authentication;
using UnityEngine;

namespace Gj.UnityCloud
{
    public class Auth
    {
        public static async Task UpdateName(string nickname)
        {
            if (string.IsNullOrEmpty(nickname) || string.IsNullOrWhiteSpace(nickname))
            {
                nickname = "体验玩家";
            }

            Debug.LogError($"Update name: {AuthenticationService.Instance.PlayerName} {nickname}");

            if (FormatName(AuthenticationService.Instance.PlayerName) != nickname)
            {
                await AuthenticationService.Instance.UpdatePlayerNameAsync(nickname);
                await Task.Delay(5000);
            }
        }

        public static bool IsLogin()
        {
            return AuthenticationService.Instance.SessionTokenExists && AuthenticationService.Instance.IsSignedIn;
        }

        public static string FormatName(string name)
        {
            if (string.IsNullOrEmpty(name) || string.IsNullOrWhiteSpace(name))
            {
                return "";
            }

            // Debug.Log($"Format name:{name} {name.Length} {name.LastIndexOf("#", StringComparison.Ordinal)} {name.Substring(0, name.LastIndexOf("#", StringComparison.Ordinal))}");
            return name.Substring(0, name.LastIndexOf("#", StringComparison.Ordinal));
        }
        
        public static async Task Login(GamePlayer player)
        {
            // 目前直接登陆unity
            // 1. 如果开通联网：绑定当前系统token
            // 2. 设定leaderboard的Meta
            // Leaderboard.Meta["nickName"] = player.Instance["nickName"];
            // Leaderboard.Meta["avatar"] = player.Instance["avatar"];
            var id = player.Instance["platform"] == "local" ? player.UserId : player.Instance["platform"].Value+":"+(player.Instance["unionId"] != null && !string.IsNullOrEmpty(player.Instance["unionId"].Value) ? player.Instance["unionId"] : player.Instance["openId"]).Value;
            
            if (AuthenticationService.Instance.SessionTokenExists)
            {
                // if not, then do nothing
                if (AuthenticationService.Instance.IsExpired)
                {
                    try
                    {
                        await AuthenticationService.Instance.SignInAnonymouslyAsync();
                        await Task.Delay(5000);
                    }
                    catch (Exception e)
                    {
                        Debug.LogError(e);
                    }
                }

                try
                {
                    var playerInfo = AuthenticationService.Instance.PlayerInfo;
                    if (playerInfo == null) playerInfo = await AuthenticationService.Instance.GetPlayerInfoAsync();
                    await Task.Delay(5000);
                    Debug.Log($"playerInfo: {playerInfo}");
                    if (playerInfo != null)
                    {
                        // foreach (var identity in playerInfo.Identities)
                        // {
                        //     Debug.Log($"identity: {identity.TypeId} {identity.UserId}");
                        // }
                        // 判断授权id是否正确
                        if (AuthenticationService.Instance.PlayerInfo.Identities?.FirstOrDefault(x => x.TypeId == "custom")?.UserId == id)
                        {
                            Debug.Log($"exist PlayerID: {AuthenticationService.Instance.PlayerId} {AuthenticationService.Instance.PlayerName}");
                            await UpdateName(player.Instance["nickName"]);

                            // 内部系统，则联机模式，关联上系统id
                            if (player.Instance["platform"] == "local")
                            {
                                // var info = await AuthenticationService.Instance.GetPlayerInfoAsync();
                                // if (info.GetOpenIdConnectId("oidc-local") == null)
                                // {
                                //     await AuthenticationService.Instance.LinkWithOpenIdConnectAsync("oidc-local", player.UserId);
                                // }
                            }
                            Debug.Log($"exist PlayerID again: {AuthenticationService.Instance.PlayerId} {AuthenticationService.Instance.PlayerName}");
                            return;
                        }
                        AuthenticationService.Instance.SignOut();
                    }
                }
                catch (Exception ee)
                {
                    Debug.LogError(ee);
                }
            }

            try
            {
                Debug.Log($"start login: {player.Instance["platform"]} {id} {player.Instance["unionId"]} {player.Instance["openId"]}");
                // await AuthenticationService.Instance
                //     .SignInWithOpenIdConnectAsync("oidc-"+player.Instance["platform"], id);
                var accessToken = await ApiNew.TokenExchange();
                Debug.Log($"start login accessToken: {accessToken}");
                var result = await ApiNew.CustomIdLogin(id, false, accessToken);
                Debug.Log($"start login custom: {id} {result} {player.Instance["nickName"]}");
                // var result = new SimpleJSON.JSONObject();
                // result["sessionToken"] = "TxMhPs6fwF9jxwTwYD-Y9Oim5PC0OpQykoVYpWJ0-9weiaX3OV6iueWuUqmKRHFa9GR_iJldDDc59bdbu0eFkmHilQrnHBXXAq7llSlclcmSAAbPeIMzYsqrKLsEjr-wuOEFTSDiEDo-F-bJrac7IRF9I7Fszms2IaS-Qq_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zUHqM2YsLTOnfOHt21rm4QJLsWhq-ii9g8SVh5EA";
                // (AuthenticationService.Instance)
                //     .CompleteSignIn(accessToken, result["sessionToken"]);
                AuthenticationService.Instance.ProcessAuthenticationTokens(accessToken, result["sessionToken"]);
                // await AuthenticationService.Instance.SignInAnonymouslyAsync();
                await UpdateName(player.Instance["nickName"]);
                
                // Shows how to get the playerID
                Debug.Log($"PlayerID: {AuthenticationService.Instance.PlayerId} {player.Instance["platform"]} {id}");
            }
            catch (AuthenticationException ex)
            {
                // Compare error code to AuthenticationErrorCodes
                // Notify the player with the proper error message
                Debug.LogException(ex);
            }
            catch (RequestFailedException ex)
            {
                // Compare error code to CommonErrorCodes
                // Notify the player with the proper error message
                Debug.LogException(ex);
            }
        }
    }
}